import { Message } from 'element-ui';
// 深拷贝一个对象

export function cloneObject(obj) {
  if (Object.prototype.toString.call(obj) !== '[object Object]') {
    return console.error('Parmas Error: An object is needed.')
  }
  let newObj = {}
  for (let key in obj) {
    newObj[key] = obj[key]
  }
  return newObj
}
// 获取token
export function getToken() {
  return sessionStorage.getItem('X-Token')
}
// 设置token
export function setToken(token) {
  sessionStorage.setItem('X-Token', token)
}
// 格式化时间戳
export function formatDate(timestamp, type) {
  type = type || '-'
  let date = new Date(Number(timestamp));
  if (date == 'Invalid Date') {
    return 'Invalid Date'
  };
  let result
  switch (type) {
    case '-':
      result = date.getFullYear() + ':' + (date.getMonth() + 1) + ':' + date.getDate()
      break
    case 'ZH':
      result = `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
      break
    case 'zh:':
      result = `${date.getFullYear()}-${formatNumber(date.getMonth() + 1)}-${formatNumber(date.getDate())} ${formatNumber(date.getHours())}:${formatNumber(date.getMinutes())}:${formatNumber(date.getSeconds())}`
      break
    default:
      break
  }
  return result
};
// 补零
const formatNumber = num => Number(num) < 10 ? '0' + num : num;
// 提示成功信息
export function notifySuccess(that, msg) {
  that.$message({
    type: 'success',
    message: msg || '操作成功!'
  })
}
// 图片转成base64
export function fileToBase64(file, callback) {
  let reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = function () {
    (typeof callback === 'function') && callback(reader.result)
  }
}
// 数组去重(数组成员是对象)
export function removeSame(arr, key) {
  if (Object.prototype.toString.call(arr) !== '[object Array]') {
    return console.error('Parma Error: The parma must be a Array!')
  }
  let obj = {}
  let result = []
  let i
  let len = arr.length
  for (i = 0; i < len; i++) {
    if (!obj[arr[i][key]]) {
      obj[arr[i][key]] = 1
      result.push(arr[i])
    }
  }
  obj = null
  return result
}
// 批量上传
export function excel2Json(file, XLSX, callback) {
  var reader = new FileReader()
  reader.onload = function (e) {
    try {
      var data = e.target.result
      var workbook = XLSX.read(data, {
        type: 'binary'
      })
      let sheets = workbook.Sheets;
      let sheet = undefined;
      for (let key in sheets) {
        (sheets[key] && Object.keys(sheets[key]).length > 1) ? (sheet = sheets[key]) : null
      };
      let res = XLSX.utils.sheet_to_json(sheet)
      if (callback) callback(workbook, res)
    } catch (e) {
      console.log(e);
      Message.error('格式化数据错误!, 请检查数据正确性')
    }
  }
  reader.readAsBinaryString(file)
};
// 根据年月日计算年龄
export function getAge(year, month, day) {
  var returnAge;
  // var strBirthdayArr=strBirthday.split("-");
  var birthYear = year;
  var birthMonth = month;
  var birthDay = day;

  var d = new Date();
  var nowYear = d.getFullYear();
  var nowMonth = d.getMonth() + 1;
  var nowDay = d.getDate();

  if (nowYear == birthYear) {
    returnAge = 0; //同年 则为0岁
  } else {
    var ageDiff = nowYear - birthYear; //年之差
    if (ageDiff > 0) {
      if (nowMonth == birthMonth) {
        var dayDiff = nowDay - birthDay; //日之差
        if (dayDiff < 0) {
          returnAge = ageDiff - 1;
        } else {
          returnAge = ageDiff;
        }
      } else {
        var monthDiff = nowMonth - birthMonth; //月之差
        if (monthDiff < 0) {
          returnAge = ageDiff - 1;
        } else {
          returnAge = ageDiff;
        }
      }
    } else {
      returnAge = -1; //返回-1 表示出生日期输入错误 晚于今天
    }
  }

  return returnAge; //返回周岁年龄

};
// 将map字符串转json
/*
'{肥胖=23, 重度生长迟缓=0, 重度消瘦=0, 消瘦=3, 生长迟缓=0, 正常=57, 超重=17, 低体重=0, 重度低体重=0}'
*/
export function mapStr2Json(mapStr) {
  if (!mapStr || mapStr === '{}') {
    return []
  };
  const returnArr = [];
  let str = mapStr.slice(1, mapStr.length - 1);
  let tempArr = str.split(', ');
  let len = tempArr.length;

  for (let i = 0; i < len; i++) {
    let curArr = tempArr[i].split('=');
    returnArr.push({
      label: curArr[0],
      rate: Number(curArr[1])
    })
  };
  return returnArr
};
// 将权限列表转为树结构
export function authList2Tree (authList) {
  return authList
    .filter(item => item.userPermissionType === '0')
    .map(item => {
      return {
        label: item.userPermissionName,
        id: item.userPermissionId,
        icon: item.userPermissionIcon,
        children: authList.filter(a => a.parentId == item.userPermissionId).map(b => {
          return {
            label: b.userPermissionName,
            id: b.userPermissionId,
            path: b.userPermissionUrl,
            children: authList.filter(c => c.parentId == b.userPermissionId).map(d => {
              return {
                label: d.userPermissionName,
                id: d.userPermissionId
              }
            })
          }
        })
      }
    });
};
